
package main;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;

/**
 * @author jp
 */
public class Pokupki extends MIDlet implements CommandListener {
    RecordStore rs;
    private final int QTY=1,
                      PRICE=2,
                      COST=3;
    Image red,
          green;
    Display display;
    List mainMenu;
    Command exit;

    Form createForm;
    Command createFormClear,
            createFormOk,
            createFormBack;
    TextField nameField,
              qtyField,
              priceField;
    int purchasesCounter=0;

    List purchaseList;
    Command purchaseListBack,
            purchaseListDeleteElement,
            purchaseListDeleteAll,
            purchaseListAdd;
    int costSum=0;
    int priceSum=0;

    Form costForm;
    int costIndex;
    TextField costField;
    Command costFormOk;
    Command costFormBack;

    public Pokupki() {
        display=Display.getDisplay(this);
        try{
            red=Image.createImage("/main/red.png");
            green=Image.createImage("/main/green.png");
        } catch(IOException ioe) {setAlert(ioe);}

        /*mainMenu=new List("Меню", List.IMPLICIT);
        mainMenu.setCommandListener(this);
        mainMenu.append("Редактировать", null);
        mainMenu.append("Список", null);
        exit=new Command("Выход", Command.EXIT, 1);
        mainMenu.addCommand(exit);*/
    }

    public void startApp() {
        setPurchaseList();
        display.setCurrent(purchaseList);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        //команды главного меню
        /*if(c==exit&&d==mainMenu) {
            destroyApp(false);
            notifyDestroyed();
        } else if(c==List.SELECT_COMMAND&&d==mainMenu) {
            switch(mainMenu.getSelectedIndex()) {
                case 0:
                    setCreateForm();
                    display.setCurrent(createForm);
                    break;
                case 1:
                    setPurchaseList();
                    display.setCurrent(purchaseList);
            }
          }*/

        //команды формы добавления пункта
        if(c==createFormBack) {
            setPurchaseList();
            display.setCurrent(purchaseList);
        }
        if(c==createFormOk) {
            String name=nameField.getString();
            String qty=qtyField.getString();
            String price=priceField.getString();

            if(name.length()>0 && qty.length()>0 && price.length()>0){
                createStore(name, qty, price);
                setCreateForm();
                display.setCurrent(createForm);
            } else {
                Alert a=new Alert("Внимание!", "Вы заполнили не все поля!", 
                        null, AlertType.INFO);
                a.setTimeout(1500);
                display.setCurrent(a);
            }
        }

        //команды списка
        if(c==exit) {
           destroyApp(false);
           notifyDestroyed();
        }
        if(c==purchaseListAdd) {
            setCreateForm();
            display.setCurrent(createForm);
        }
        if(c==purchaseListDeleteElement && purchasesCounter>0) {
            String storeName=RecordStore.listRecordStores()[
                    purchaseList.getSelectedIndex()];
            try{
                RecordStore.deleteRecordStore(storeName);
            } catch(Exception e) {setAlert(e);}
            setPurchasesCounter();
            setPurchaseList();
            display.setCurrent(purchaseList);
        } else if(c==purchaseListDeleteElement) { //если список пуст
            Alert a=new Alert(
                    "Внимание!", "Список пуст!", null, AlertType.INFO);
            a.setTimeout(1000);
            display.setCurrent(a);
        }
        if(c==purchaseListDeleteAll && purchasesCounter>0) {
            for(int i=RecordStore.listRecordStores().length; i>0; i--) {
                String storeName=RecordStore.listRecordStores()[i-1];
                try {
                    RecordStore.deleteRecordStore(storeName);
                } catch(Exception e) {setAlert(e);}
            }
            setPurchaseList();
            display.setCurrent(purchaseList);
        } else if(c==purchaseListDeleteAll) { //если список пуст
            Alert a=new Alert(
                    "Внимание!", "Список пуст!", null, AlertType.INFO);
            a.setTimeout(1000);
            display.setCurrent(a);
        }

        //команды пункта списка
        if(c==List.SELECT_COMMAND&&d==purchaseList) {
            int i=purchaseList.getSelectedIndex();
            String cost="";
            //проверка, не куплено ли уже
            try {
                /*rs.closeRecordStore();*/
                rs=RecordStore.openRecordStore(
                        RecordStore.listRecordStores()[i], false);
                cost=new String(rs.getRecord(COST), "UTF8");
                rs.closeRecordStore();
            } catch(Exception e) {setAlert(e);}
            if(cost.equals("-1")) {
                setCostForm(i);
                costIndex=i;
                display.setCurrent(costForm);
            } else {
                Alert a=new Alert("Внимание!", "Уже куплено!",
                        null, AlertType.INFO);
                a.setTimeout(1000);
                display.setCurrent(a);
            }
        }

        //команды формы покупки
        if(c==costFormBack) {
            display.setCurrent(purchaseList);
        }
        if (c==costFormOk && costField.getString().length()>0) {
            setCost(costIndex, costField.getString());
            setPurchaseList();
            display.setCurrent(purchaseList);
        } else if(c==costFormOk && costField.getString().length()==0) {
            Alert a=new Alert("Внимание", "Вы не ввели стоимость!",
                    null, AlertType.INFO);
            a.setTimeout(1000);
            display.setCurrent(a);
        }
    }

    private void setCreateForm() {
        setPurchasesCounter();
        createForm=new Form(
                "Добавить (всего: " +
                 String.valueOf(purchasesCounter) +
                ")");
        createFormOk=new Command("OK", Command.OK, 1);
        createFormBack=new Command("Готово", Command.BACK, 1);
        createFormClear=new Command("Очистить", Command.EXIT, 1);
        createForm.addCommand(createFormOk);
        createForm.addCommand(createFormBack);
        createForm.addCommand(createFormClear);
        createForm.setCommandListener(this);
        nameField=new TextField(
                "Наименование", "", 20, TextField.ANY);
        qtyField=new TextField(
                "Количество", "", 6, TextField.ANY);
        priceField=new TextField(
                "Цена", "", 4, TextField.NUMERIC);
        createForm.append(nameField);
        createForm.append(qtyField);
        createForm.append(priceField);
    }

    private void setPurchaseList() {
        setPriceSum();
        setCostSum();
        purchaseList=new List("Список "
                    + "($: "+ String.valueOf(costSum) + "/" +
                    String.valueOf(priceSum) + ")",
                    List.IMPLICIT);
        purchaseList.setFitPolicy(List.TEXT_WRAP_ON);
        purchaseList.setCommandListener(this);
        purchaseListAdd=new Command("Добавить пункт", Command.EXIT, 0);
        exit=new Command("Выход", Command.BACK, 1);
        purchaseListDeleteElement=new Command("Удалить пункт", Command.EXIT, 1);
        purchaseListDeleteAll=new Command("Удалить всё", Command.EXIT, 2);
        purchaseList.addCommand(exit);
        purchaseList.addCommand(purchaseListDeleteElement);
        purchaseList.addCommand(purchaseListDeleteAll);
        purchaseList.addCommand(purchaseListAdd);
        try{
            for(int i=0; i<purchasesCounter; i++) {
                String storeName=RecordStore.listRecordStores()[i];
                rs=RecordStore.openRecordStore(storeName, false);
                String price=new String(rs.getRecord(PRICE), "UTF8");
                String qty=new String(rs.getRecord(QTY), "UTF8");
                String cost=new String(rs.getRecord(COST), "UTF8");
                String toAppend=
                        storeName + " (" + qty + ")\n" + price + " руб.";
                if(cost.equals("-1"))
                    purchaseList.append(toAppend, red);
                else
                    purchaseList.append(toAppend, green);
                    rs.closeRecordStore(); //??????????????????????
            }
        } catch(Exception e) {setAlert(e);}
    }

    private void setCostForm(int i) {
        String storeName=RecordStore.listRecordStores()[i];
        costForm=new Form(storeName);
        costField=new TextField(
                "Эта покупка стоила", "", 4, TextField.DECIMAL);
        costForm.append(costField);
        costFormOk=new Command("Куплено", Command.OK, 1);
        costFormBack=new Command("Назад", Command.BACK, 1);
        costForm.addCommand(costFormOk);
        costForm.addCommand(costFormBack);
        costForm.setCommandListener(this);
    }

    private void setPriceSum() {
        priceSum=0; //сбрасываем счётчик, чтоб не приплюсовывал постоянно
        setPurchasesCounter();
        for(int i=0; i<purchasesCounter; i++) {
            String storeName=RecordStore.listRecordStores()[i];
            try {
                rs=RecordStore.openRecordStore(storeName, false);
                int toSum=Integer.parseInt(
                        new String(rs.getRecord(PRICE), "UTF8"));
                priceSum+=toSum;
                rs.closeRecordStore();
            } catch(Exception e) {setAlert(e);}
        }
    }

    private void setCostSum() {
        costSum=0; //сбрасываем счётчик, что б не приплюсовывал постоянно
        setPurchasesCounter();
        for(int i=0; i<purchasesCounter; i++) {
            String storeName=RecordStore.listRecordStores()[i];
            try {
                rs=RecordStore.openRecordStore(storeName, false);
                int toSum=Integer.parseInt(
                        new String(rs.getRecord(COST), "UTF8"));
                if(toSum>=0) {
                    costSum+=toSum;
                    rs.closeRecordStore();
                } else {
                    rs.closeRecordStore();
                    continue;
                }
            } catch(Exception e) {setAlert(e);}
        }
    }

    private void setAlert(Exception e) {
        Alert a=new Alert("Сообщите разработчику!", e.getMessage(),
                null, AlertType.ERROR);
        a.setTimeout(1500);
        display.setCurrent(a);
    }

    private void createStore(String name, String qty, String price) {
        try {
            byte[] qtyBytes=qty.getBytes("UTF8"),
                   priceBytes=price.getBytes("UTF8"),
                   costBytes="-1".getBytes("UTF8");
            rs=RecordStore.openRecordStore(name, true,
                    RecordStore.AUTHMODE_ANY, false);
            rs.addRecord(qtyBytes, 0, qtyBytes.length);
            rs.addRecord(priceBytes, 0, priceBytes.length);
            rs.addRecord(costBytes, 0, costBytes.length);
            rs.closeRecordStore();
        } catch(Exception e) {setAlert(e);}
    }

    /**
     *
     * @param index индекс текущего номера списка
     * @param cost значение стоимости в виде строки
     */
    private void setCost(int index, String cost) {
        String storeName=RecordStore.listRecordStores()[index];
        try {
            byte[] costBytes=cost.getBytes("UTF8");
            rs=RecordStore.openRecordStore(storeName, false);
            rs.setRecord(COST, costBytes, 0, costBytes.length);
            rs.closeRecordStore();
        } catch(Exception e) {setAlert(e);}
    }

    public void setPurchasesCounter() {
        if(RecordStore.listRecordStores()==null)
            purchasesCounter=0;
        else
            purchasesCounter=RecordStore.listRecordStores().length;
    }
}
